package cn.wolfcode.rbac.web.controller;

import cn.wolfcode.rbac.domain.Customer;
import cn.wolfcode.rbac.domain.Employee;
import cn.wolfcode.rbac.query.CustomerQuery;
import cn.wolfcode.rbac.service.ICustomerService;
import cn.wolfcode.rbac.service.IEmployeeService;
import cn.wolfcode.rbac.service.ISystemDictionaryItemService;
import cn.wolfcode.rbac.util.JsonResult;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/customer")
public class CustomerController {
    
    @Autowired
    private ICustomerService customerService;

    @Autowired
    private IEmployeeService employeeService;

    @Autowired
    private ISystemDictionaryItemService dictionaryItemService;

    // 提供一个方法处理查询所有部门数据请求，响应 HTML
    @RequestMapping("/list")
    //@RequiredPermission(name="部门列表")
    // qo 要贴注解，@ModelAttribute 将数据添加到模型对象中，等价于 model.addAttribute("attributeName", qo);
    public String list(Model model,@ModelAttribute("qo") CustomerQuery qo){
        // 根据状态查询客户
        String[] statuses = {"潜在客户","正式客户","开发失败","流失客户","客户池"};
        model.addAttribute("statuses",statuses);

        // 根据角色编码查询拥有该角色的员工 Market Market_Manager
        List<Employee> employees = employeeService.selectByRoleSn("Market", "Market_Manager");
        model.addAttribute("employees",employees);

        PageInfo result = customerService.query(qo);
        model.addAttribute("result", result);
        return "customer/list"; // /WEB-INF/views/customer/list3.ftl
    }

    @RequestMapping("/potentialList")
    public String potentialList(Model model,@ModelAttribute("qo") CustomerQuery qo){
        // 只查询潜在客户状态
        qo.setStatus(Customer.STATUS_COMMON);
        // 如果登录的员工是管理员或经理，就可以看所有的客户；普通的销售人员，只能看自己的客户，不能看别人的
        Subject subject = SecurityUtils.getSubject();
        if(!(subject.hasRole("admin") || subject.hasRole("Market_Manager"))){
            // 获取当前登录用户id
            Employee employee = (Employee)subject.getPrincipal();
            Long id = employee.getId();
            // 根据当前员工id查询所跟进的客户
            qo.setSellerId(id);
        }
        // 根据角色编码查询拥有该角色的员工 Market Market_Manager
        List<Employee> employees = employeeService.selectByRoleSn("Market", "Market_Manager");
        model.addAttribute("employees",employees);

        // 职业下拉框数据
        model.addAttribute("jobs",dictionaryItemService.selecteByDiSn("job"));

        // 来源下拉框数据
        model.addAttribute("source",dictionaryItemService.selecteByDiSn("source"));

        // 交流方式下拉框数据
        model.addAttribute("communicationMethods",dictionaryItemService.selecteByDiSn("communicationMethod"));
        PageInfo result = customerService.query(qo);
        model.addAttribute("result", result);
        return "customer/potentialList"; // /WEB-INF/views/customer/list3.ftl
    }


    @RequestMapping("/saveOrUpdate")
    @ResponseBody   // 告诉 Spring MVC，我们需要转为 json格式返回给前端
    public JsonResult saveOrUpdate(Customer customer){
            if(customer.getId() == null){ // 代表新增
                customerService.save(customer);
            }else { // 代表修改
                customerService.update(customer);
            }
            return new JsonResult();
        //return "redirect:/customer/list.do";  // http://localhost/customer/list.do
    }


    @RequestMapping("/delete")
    @ResponseBody
    public JsonResult delete(Long id){
        // int i = 1/0;
        try {
            if (id != null) {
                customerService.delete(id);
            }
            return new JsonResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(false,"操作失败！");
        }
    }

    /**
     * 手机号远程验证是否存在
     * 返回 Map true 代表验证通过（不存在），false 代表 验证不通过（存在）
     * @param tel
     * @return
     */
    @RequestMapping("/checkTel")
    @ResponseBody
    public Map<String,Boolean> checkTel(String tel, Long id){   // valid：true(插件要求的（remote.php 可以看到）)
        // 判断新增（id==null）还是编辑
        HashMap<String, Boolean> map = new HashMap<>();
        if(id == null){
            String customer = customerService.selectByTel(tel); // 这里的返回类型可以为String
            map.put("valid",customer==null);
        }else {
            // 根据 id 查询手机号码
            String oldTel = customerService.get(id).getTel();
            String newTel = customerService.selectByTel(tel);
            if(oldTel == newTel){  // 判断手机号有没有改变
                map.put("valid",true);
            }else {
                // 判断现在的手机号码是不是存在数据库
                map.put("valid",customerService.selectByTel(tel) == null);
            }
        }
        return map;
    }
}
